package com.missfresh.cooperation2meituan.controller;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.missfresh.cooperation2meituan.runner.HandleOrderRunner;
import com.missfresh.cooperation2meituan.service.OrderService;
import com.missfresh.cooperation2meituan.util.CommonUtil;
import com.missfresh.cooperation2meituan.util.JsonUtil;
import com.missfresh.cooperation2meituan.vo.OrderDetail;
import com.missfresh.cooperation2meituan.vo.SysOrderDetail;
import com.missfresh.cooperation2meituan.vo.SystemParams;

@Controller
@RequestMapping("order")
public class OrderController {
	
	private static final Logger logger = LoggerFactory.getLogger(OrderController.class);
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private HandleOrderRunner runner;
	
	/**
	 * 接收美团外卖推送订单接口
	 * 
	 */
	
	@ResponseBody
	@RequestMapping(value="/receive.do", method=RequestMethod.POST, produces="application/json;charset=utf-8")
	public Object  receive(HttpServletRequest request,
			@RequestParam("app_id") String app_id,
			@RequestParam("timestamp") String timestamp,
			@RequestParam("sig") String sig) {
		
		logger.info("接收美团外卖订单开始");
		String order_id = request.getParameter("order_id");
		String wm_order_id_view = request.getParameter("wm_order_id_view");
		String app_poi_code = request.getParameter("app_poi_code");
		String wm_poi_id = request.getParameter("wm_poi_id");
		String wm_poi_name = urlUncode(request.getParameter("wm_poi_name"));
		String wm_poi_address = urlUncode(request.getParameter("wm_poi_address"));
		String wm_poi_phone = request.getParameter("wm_poi_phone");
		String recipient_address = urlUncode(request.getParameter("recipient_address"));
		String recipient_phone = request.getParameter("recipient_phone");
		String recipient_name = urlUncode(request.getParameter("recipient_name"));
		String shipping_fee = request.getParameter("shipping_fee");
		String total = request.getParameter("total");
		String original_price = request.getParameter("original_price");
		String caution = urlUncode(request.getParameter("caution"));
		String shipper_phone = request.getParameter("shipper_phone");
		String status = request.getParameter("status");
		String has_invoiced = request.getParameter("has_invoiced");
		String invoice_title = urlUncode(request.getParameter("invoice_title"));
		String ctime = request.getParameter("ctime");
		String utime = request.getParameter("utime");
		String delivery_time = request.getParameter("delivery_time");
		String is_third_shipping = request.getParameter("is_third_shipping");
		String pay_type = request.getParameter("pay_type");
		String latitude = request.getParameter("latitude");
		String longitude = request.getParameter("longitude");
		String avg_send_time = request.getParameter("avg_send_time");
		String city_id = request.getParameter("city_id");
		String detail = urlUncode(request.getParameter("detail"));
		String extras = urlUncode(request.getParameter("extras"));
		//验证签名
		List<String> list = new ArrayList<String>();
		list.add("app_id="+app_id);
		list.add("timestamp="+timestamp);
		list.add("order_id="+order_id);
		list.add("wm_order_id_view="+wm_order_id_view);
		list.add("app_poi_code="+app_poi_code);
		list.add("wm_poi_id="+wm_poi_id);
		list.add("wm_poi_name="+wm_poi_name);
		list.add("wm_poi_address="+wm_poi_address);
		list.add("wm_poi_phone="+wm_poi_phone);
		list.add("recipient_address="+recipient_address);
		list.add("recipient_phone="+recipient_phone);
		list.add("recipient_name="+recipient_name);
		list.add("shipping_fee="+shipping_fee);
		list.add("total="+total);
		list.add("original_price="+original_price);
		list.add("caution="+caution);
		list.add("shipper_phone="+shipper_phone);
		list.add("status="+status);
		list.add("has_invoiced="+has_invoiced);
		list.add("invoice_title="+invoice_title);
		list.add("ctime="+ctime);
		list.add("utime="+utime);
		list.add("delivery_time="+delivery_time);
		list.add("is_third_shipping="+is_third_shipping);
		list.add("pay_type="+pay_type);
		list.add("latitude="+latitude);
		list.add("longitude="+longitude);
		list.add("avg_send_time="+avg_send_time);
		list.add("city_id="+city_id);
		list.add("detail="+detail);
		list.add("extras="+extras);
		if(orderService.checkSig(list,sig)){
			logger.info("美团外卖订单签名认证成功");
			//保存美团外卖下单数据
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("order_id",order_id);
			map.put("wm_order_id_view",wm_order_id_view);
			map.put("app_poi_code",app_poi_code);
			map.put("wm_poi_name",wm_poi_name);
			map.put("wm_poi_address",wm_poi_address);
			map.put("wm_poi_phone",wm_poi_phone);
			map.put("recipient_address",recipient_address);
			map.put("recipient_phone",recipient_phone);
			map.put("recipient_name",recipient_name);
			map.put("shipping_fee",shipping_fee);
			map.put("total",total);
			map.put("original_price",original_price);
			map.put("caution",caution);
			map.put("shipper_phone",shipper_phone);
			map.put("status",status);
			map.put("has_invoiced",has_invoiced);
			map.put("invoice_title",invoice_title);
			map.put("ctime",ctime);
			map.put("utime",utime);
			map.put("delivery_time",delivery_time);
			map.put("is_third_shipping",is_third_shipping);
			map.put("pay_type",pay_type);
			map.put("latitude",latitude);
			map.put("longitude",longitude);
			map.put("detail",detail);
			map.put("extras",extras);
			if(orderService.addOrder(map)){
				logger.info("美团外卖订单保存成功");
				//保存成功后，开始处理下单流程
				try {
					List<OrderDetail> details = JsonUtil.json2list(detail, OrderDetail.class);
					Map<String, Object> ordermap = new HashMap<String, Object>();
					String warehouse = (String) orderService.queryStoreCode(app_poi_code).get("wma_store_code");
					ordermap.put("warehouse", warehouse);
					ordermap.put("t_id", order_id);
					ordermap.put("send_time", CommonUtil.dateToString(new Date()));
					ordermap.put("fromERP", "AS_POP");
					ordermap.put("shop_code", "club_meituan");
					List<Map<String, String>> outers = new ArrayList<Map<String,String>>();
					List<SysOrderDetail> orders = new ArrayList<SysOrderDetail>();
					BigDecimal sum_num = new BigDecimal(0);
					BigDecimal sum_discount_fee = new BigDecimal(0);
					for(int i=0;i<details.size();i++){
						SysOrderDetail sysorderdel = new SysOrderDetail();
						sysorderdel.setOuter_item_id(details.get(i).getSku_id());
						sysorderdel.setNum(details.get(i).getQuantity());
						sysorderdel.setPrice(details.get(i).getPrice());
						sysorderdel.setTitle(details.get(i).getFood_name());
						BigDecimal discount_fee = (new BigDecimal(0));
						if(new BigDecimal(1).compareTo(details.get(i).getFood_discount())==1){
							BigDecimal a = details.get(i).getFood_discount().multiply(new BigDecimal(10));
							BigDecimal b = new BigDecimal(10).subtract(a);
							BigDecimal c = b.multiply(details.get(i).getPrice());
							discount_fee = c.divide(new BigDecimal(10));
						}
						sysorderdel.setDiscount_fee(discount_fee);
						sysorderdel.setPayment(details.get(i).getPrice().subtract(discount_fee));
						sysorderdel.setTotal_fee(details.get(i).getPrice().multiply
								(new BigDecimal(details.get(i).getQuantity())));
						orders.add(sysorderdel);
						sum_num = sum_num.add(new BigDecimal(details.get(i).getQuantity()));
						sum_discount_fee = sum_discount_fee.add(discount_fee);
						Map<String, String> outersmap = new HashMap<String, String>();
						outersmap.put("outer_id", details.get(i).getSku_id());
						outersmap.put("quantity", details.get(i).getQuantity()+"");
						outers.add(outersmap);
					}
					ordermap.put("outers", outers);
					Map<String, Object> maordermap = new HashMap<String, Object>();
					maordermap.put("t_id", wm_order_id_view);
					maordermap.put("total_fee", total);
					maordermap.put("created", ctime);
					maordermap.put("lat", latitude);
					maordermap.put("pay_time", ctime);
					maordermap.put("receiver_mobile", recipient_phone);
					maordermap.put("receiver_address", recipient_address);
					maordermap.put("receiver_name", recipient_name);
					maordermap.put("lng", longitude);
					maordermap.put("post_fee", shipping_fee);
					maordermap.put("pay_type", pay_type);
					maordermap.put("delivery_time", ctime);
					maordermap.put("station_code", (String) orderService.queryStoreCode(app_poi_code).get("tms_store_code"));
					maordermap.put("tms_store_code", "");
					maordermap.put("num", sum_num);
					maordermap.put("discount_fee", sum_discount_fee);
					maordermap.put("payment", new BigDecimal(total).subtract(sum_discount_fee));
					maordermap.put("orders", orders);
					Map<String, Object> param = new HashMap<String, Object>();
					param.put("ordermap", ordermap);
					param.put("maordermap", maordermap);
					runner.setParam(param);
					new Thread(runner).start();
				} catch (Exception e) {
					e.printStackTrace();
				}
				return "{\"data\": \"ok\"}";
				
			}else{
				return "{\"data\":\"ng\",\"error\":{\"code\":600,\"msg\":\"系统内部错误\"}}";
			}
				
		}else{
			logger.info("美团外卖订单签名认证失败");
			return "{\"data\":\"ng\",\"error\":{\"code\":703,\"msg\":\"签名验证错误\"}}";
		}
	}
	
	@ResponseBody
	@RequestMapping(value="/cancel.do", method=RequestMethod.GET)
	public Object  cancel(@RequestParam("order_id") String order_id,
			@RequestParam("reason_code") String reason_code,
			@RequestParam("reason") String reason,SystemParams sysparams) {
		logger.info("接收美团外卖取消订单");
		
		return "{\"data\": \"ok\"}";
	}
	
	@ResponseBody
	@RequestMapping(value="/test.do", method=RequestMethod.POST)
	public Object  test(@RequestParam(value="param", required=true) String param,
			@RequestBody String body) {
		logger.info("test"+param);
		logger.info("body"+body);
		return "{\"data\": \"ok\"}";
	}
	
	public String urlUncode(String param){
		String result = "";
		try {
			result =java.net.URLDecoder.decode(param,"utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	
}
